//使用惰性单例模式实现只请求一次权限

export default {
//管理单例
  getSingle(fn) {
    var result;
    return function () {
      return result || (result = fn.apply(this,arguments))
    }
  },

  getAuthorityFunc() {
    var userInfo = null;
    var access_token = localStorage.getExpire("access_token");
    if(access_token){
      userInfo=localStorage.getExpire("userInfo");
    }
    return userInfo;
  },

//获取权限
  getAuthority() {
    return this.getSingle(this.getAuthorityFunc());
  },

// window.onload=function(){
//     //示例获取权限方法
//     var data1 = getAuthority()
// };


  //注销方法
  loginOutFunc(){
    localStorage.clear();
    top.location.href=loginPageUrl;
  }

}

Storage.prototype.getExpire = key => {
  let val = localStorage.getItem(key);
  if (!val) {
    return val;
  }
  val = JSON.parse(val);
  if (Date.now() - val.time > val.expire) {
    localStorage.removeItem(key);
    return null;
  }else{
    var obj = {
      data: val.data,
      time: Date.now(),
      expire: val.expire
    }
    localStorage.setItem(key,JSON.stringify(obj));
  }
  return val.data;
}

Storage.prototype.setExpire = (key, value, expire) => {
  let obj = {
    data: value,
    time: Date.now(),
    expire: expire
  };
  //localStorage 设置的值不能为对象,转为json字符串
  localStorage.setItem(key, JSON.stringify(obj));
}
